defmodule House.Web.PhotoController do
  use House.Web, :controller

  alias House.BasicData

  def index(conn, %{"item_id" => item_id}) do
    photos = BasicData.list_photos(item_id)
    item = BasicData.get_item!(item_id)
    changeset = BasicData.change_photo(%House.BasicData.Photo{})

    render(conn, "index.html", photos: photos, item: item, changeset: changeset)
  end

  def create(conn, %{"photo" => photo_params, "item_id" => item_id}) do
    item = BasicData.get_item!(item_id)
    policy = Qiniu.PutPolicy.build("scope")
    uptoken = Qiniu.Auth.generate_uptoken(policy)
    put_policy = Qiniu.PutPolicy.build("house")

    Enum.each photo_params["photos"], fn photo ->
      upload = photo[""]
      {filename, url} = House.Web.PhotoView.qiniu_file_and_url(upload)
      Qiniu.Uploader.upload put_policy, upload.path, key: filename

      photo_params = %{
        url: url,
        kind: photo_params["kind"]
      }
      BasicData.create_photo(item.id, photo_params)
    end

    redirect conn, to: item_photo_path(conn, :index, item)
  end

  def update(conn, %{"id" => id, "photo" => photo_params}) do
    photo = BasicData.get_photo!(id)

    case BasicData.update_photo(photo, photo_params) do
      {:ok, photo} ->
        conn
        |> put_flash(:info, "Photo updated successfully.")
        |> redirect(to: photo_path(conn, :show, photo))
      {:error, %Ecto.Changeset{} = changeset} ->
        render(conn, "edit.html", photo: photo, changeset: changeset)
    end
  end

  def delete(conn, %{"id" => id}) do
    photo = BasicData.get_photo!(id)
    {:ok, _photo} = BasicData.delete_photo(photo)

    conn
    |> put_flash(:info, "Photo deleted successfully.")
    |> redirect(to: item_photo_path(conn, :index, BasicData.get_item!(photo.item_id) ))
  end
end
